package cn.ccbfund.demo.service.impl;

import java.util.ArrayList;
import java.util.Date;
import java.util.List;
import java.util.UUID;

import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.BeanUtils;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import com.baomidou.mybatisplus.enums.SqlLike;
import com.baomidou.mybatisplus.mapper.EntityWrapper;
import com.baomidou.mybatisplus.plugins.Page;
import com.baomidou.mybatisplus.service.impl.ServiceImpl;

import cn.ccbfund.common.util.UserUtils;
import cn.ccbfund.demo.entity.Demo;
import cn.ccbfund.demo.model.DemoMO;
import cn.ccbfund.demo.mapper.DemoMapper;
import cn.ccbfund.demo.service.DemoService;
 
@Service
@Transactional
public class DemoServiceImpl extends ServiceImpl<DemoMapper, Demo> implements DemoService {
 
	@Override
	public Page<DemoMO> queryDemoMO(Integer currentPage, Integer pageSize, String name, String code){
	  	EntityWrapper<Demo> ew = new EntityWrapper<>();
	  	if (StringUtils.isNotBlank(code)) {
			 ew.like(Demo.CODE, code, SqlLike.DEFAULT);
		}
       	if (StringUtils.isNotBlank(name)) {
        	ew.like(Demo.NAME, name, SqlLike.DEFAULT);
        }
        ew.orderBy(Demo.CREATE_TIME, false);
        Page<Demo> page = this.selectPage(new Page<Demo>(currentPage, pageSize), ew);
        List<Demo> records = page.getRecords();
        
        Page<DemoMO> ret = new Page<>(currentPage, pageSize);
		ret.setTotal(page.getTotal());
		List<DemoMO> list = new ArrayList<>();
		for(Demo bean : records) {
			list.add(getProperties(bean));
		}
		ret.setRecords(list);
		ret.getPages();
        return ret;
	}

  	private DemoMO getProperties(Demo bean){
      DemoMO mo = new DemoMO();
      BeanUtils.copyProperties(bean, mo);	
      
      return mo;	
    }
    
	private void check(DemoMO bean) {
	
	}
	
	private void setProperties(DemoMO bean){
      
    }
    
    @Override
	public Boolean syncDemoMO(DemoMO bean){
    	return true;
	}
	
	@Override
	public Boolean insertDemoMO(DemoMO bean) {
		check(bean);
		
		setProperties(bean);
		
		bean.setId(UUID.randomUUID().toString());
		bean.setCreateUser(UserUtils.getUser());
		bean.setCreateTime(new Date());    	
		return this.insert(bean);
	}
	
	@Override
	public Boolean updateDemoMOById(DemoMO bean) {
		check(bean);
		
		setProperties(bean);
		
		bean.setUpdateUser(UserUtils.getUser());
		bean.setUpdateTime(new Date());
		return this.updateById(bean);
	}

	@Override
	public Boolean deleteDemoMOById(String id) {
		return this.deleteById(id);
	} 
}
